<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <div class="area-header">
        <span class="area-header-title">{{ $t('账套信息') }}</span>
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('账套编号')" prop="accountCode">
            <el-input v-model="form.accountCode" :placeholder="$t('账套编号')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('账套名称')" prop="accountName">
            <el-input v-model="form.accountName" :placeholder="$t('账套名称')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('账套全称')" prop="accountFullName">
            <el-input v-model="form.accountFullName" :placeholder="$t('账套全称')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('账套启用年月')" prop="startYearMonth">
            <el-date-picker
              v-model="form.startYearMonth"
              :clearable="false"
              type="month"
              value-format="yyyy-MM"
              :placeholder="$t('账套启用年月')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('会计标准')" prop="accountingStandard">
            <el-select v-model="form.accountingStandard" disabled>
              <el-option v-for="item in accountingStandardOption" :key="item.id" :label="item.tempName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('基金信息') }}</span>
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('基金名称')" prop="fundId">
            <MainBodySelect
              v-model="form.fundId"
              parameters="fund"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('初始份额') + $t('金额单位')" prop="initialShare">
            <Money v-model="form.initialShare" :placeholder="$t('初始份额')" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('初始金额') + $t('金额单位')" prop="initialMoney">
            <Money v-model="form.initialMoney" :placeholder="$t('初始金额')" unit="w" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('账套管理明细') }}</span>
        <el-button size="small" type="text" icon="el-icon-edit" @click="createNewSubject()">{{ $t('新增科目') }}</el-button>
      </div>
      <el-radio-group v-model="subjectType" size="small" class="subjectCode mb15">
        <el-radio-button v-for="dict in subjectTypeOptions" :key="dict.dictValue" :label="dict.dictValue" @click.native.prevent="radioChange(dict.dictValue)">{{ $t(dict.dictLabel) }}</el-radio-button>
      </el-radio-group>
      <div>
        <el-table ref="table" v-loading="loading" :data="form.finFundAccountDetailList" tooltip-effect="darkTable" row-key="id" border default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column :label="$t('科目编码')" prop="subjectCode" show-overflow-tooltip min-width="180" />
          <el-table-column :label="$t('科目名称')" prop="subjectName" show-overflow-tooltip />
          <el-table-column :label="$t('科目类别')" align="center" prop="subjectType" :formatter="subjectTypeFormat" />
          <el-table-column :label="$t('余额方向')" align="center" prop="balanceDirection" :formatter="balanceDirectionFormat" />
          <el-table-column :label="$t('排序')" align="center" prop="sort" />
          <el-table-column :label="$t('期初金额')" align="center" prop="openingAmount">
            <template slot-scope="scope">
              <template v-if="isNoChildren(scope.row)">
                <Money v-model="scope.row.openingAmount" :disabled="scope.row.parentId==='0' ? true : false" :placeholder="$t('期初金额')" @change="onChange(scope.row)" />
              </template>
              <template v-else>
                {{ countHj(scope.row) }}
              </template>
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="280">
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                icon="el-icon-edit"
                @click="updateHandle(scope.row)"
              >{{ $t('修改') }}
              </el-button>
              <el-button
                size="small"
                type="text"
                icon="el-icon-edit"
                @click="createNextLevel(scope.row)"
              >{{ $t('新增下一级') }}
              </el-button>
              <el-button
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="deleteHandle(scope.row)"
              >{{ $t('删除') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="fin:fundAccount" />
    </div>
    <!-- 添加或修改财务核心-基金账套明细对话框 -->
    <el-dialog :title="$t('科目管理')" :visible.sync="subjectOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <finFundAccountDetailForm ref="finFundAccountDetailForm" @setTreeData="setTreeData" />
    </el-dialog>
  </div>
</template>

<script>
    import { saveFinFundAccount, getFinFundAccount } from '@/api/fin/fundAccount/finFundAccount'
    import MainBodySelect from '@/components/MainBodySelect/index.vue'
    import { getSubjectTreeData } from '@/api/fin/subjectManage/finSubjectManage'
    import finFundAccountDetailForm from '@/views/fin/fundAccount/finFundAccountDetailForm.vue'
    import { delFormFinFundAccountDetail } from '@/api/fin/fundAccount/finFundAccountDetail'
    import { findTempList } from '@/api/fin/sysTemp/finSysAccountTemp'
    export default {
      components: { finFundAccountDetailForm, MainBodySelect },
        data() {
            return {
                // 表单参数
                form: {
                  finFundAccountDetailList: []
                },
                // 遮罩层
                loading: false,
                subjectOpen: false,
                // 表单校验
                rules: {
                  accountCode: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  accountName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  accountFullName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  startYearMonth: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  accountingStandard: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                  // fundId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
                // 科目类别字典
                subjectTypeOptions: [],
                // 余额方向字典
                balanceDirectionOptions: [],
                finSubjectManageCacheList: [],
                accountingStandardOption: [],
                subjectType: ''
            }
        },
        created() {
          this.getDicts('subject_category').then(response => {
            this.subjectTypeOptions = response.data
          })
          this.getDicts('balance_direction').then(response => {
            this.balanceDirectionOptions = response.data
          })
          // 查询会计准则模板
          findTempList().then(res => {
            this.accountingStandardOption = res.data
          })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                this.subjectType = ''
                if (data != null && data.id !== undefined) {
                    getFinFundAccount(data.id).then(response => {
                        this.form = response.data
                        this.finSubjectManageCacheList = JSON.parse(JSON.stringify(this.form.finFundAccountDetailList))
                        this.loading = false
                    }).catch(() => {
                      this.loading = false
                    })
                } else {
                    this.reset()
                    this.getSubjectTreeList()
                    this.loading = false
                }
            },
            /** 查询财务核心-科目管理列表 */
            getSubjectTreeList() {
              getSubjectTreeData(this.queryParams).then(response => {
                this.form.finFundAccountDetailList = response.data || []
                this.finSubjectManageCacheList = JSON.parse(JSON.stringify(this.form.finFundAccountDetailList))
              })
            },
            // 科目类别字典翻译
            subjectTypeFormat(row) {
              return this.selectDictLabel(this.subjectTypeOptions, row.subjectType)
            },
            // 余额方向字典翻译
            balanceDirectionFormat(row) {
              return this.selectDictLabel(this.balanceDirectionOptions, row.balanceDirection)
            },
            /** 修改按钮操作 */
            updateHandle(row) {
              this.subjectOpen = true
              this.$nextTick(() => {
                // 调用form页面的 init 方法初始化数据
                this.form.finFundAccountDetailList = JSON.parse(JSON.stringify(this.form.finFundAccountDetailList))
                this.$refs.finFundAccountDetailForm.init(row, this.form.finFundAccountDetailList, 'edit')
              })
            },
            // 添加下一级科目按钮操作
            createNextLevel(row) {
              this.subjectOpen = true
              this.$nextTick(() => {
                this.$refs.finFundAccountDetailForm.nextInit(row, this.form.finFundAccountDetailList, 'add')
              })
            },
            // 添加新的科目按钮操作
            createNewSubject() {
              this.subjectOpen = true
              this.$nextTick(() => {
                this.$refs.finFundAccountDetailForm.nextNewInit(this.subjectType, this.form.finFundAccountDetailList, 'newAdd')
              })
            },
            // 下一级表单页面点击添加按钮时调用，在tree树下添加新的对应节点
            setTreeData(data) {
              this.setChildrenTreeData(data, this.form.finFundAccountDetailList, data.operateType)
              this.setChildrenTreeData(data, this.finSubjectManageCacheList, data.operateType)
              this.form.finFundAccountDetailList = JSON.parse(JSON.stringify(this.form.finFundAccountDetailList))
              this.finSubjectManageCacheList = JSON.parse(JSON.stringify(this.finSubjectManageCacheList))
            },
            // 下一级表单页面点击添加按钮时调用，在tree树下添加新的对应节点
            setChildrenTreeData(data, list, operateType) {
              if (operateType === 'newAdd') {
                list.push(data)
              } else {
                const length = list.length
                if (length > 0) {
                  for (let i = 0; i < length; i++) {
                    const item = list[i]
                    if (operateType === 'edit') {
                      if (data.id === item.id) {
                        item.parentId = data.parentId
                        item.subjectCode = data.subjectCode
                        item.subjectName = data.subjectName
                        item.subjectType = data.subjectType
                        item.balanceDirection = data.balanceDirection
                        item.openingAmount = data.openingAmount
                        item.auxiliaryAccounting = data.auxiliaryAccounting
                        item.sort = data.sort
                        break
                      } else {
                        this.setChildrenTreeData(data, item.children, operateType)
                      }
                    } else if (operateType === 'add') {
                      if (data.parentId === item.id) {
                        item.children.push(data)
                        break
                      } else {
                        this.setChildrenTreeData(data, item.children, operateType)
                      }
                    }
                  }
                }
              }
            },
            /** 删除按钮操作 */
            deleteHandle(row) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              }).then(() => {
                delFormFinFundAccountDetail(row.id).then((res) => {
                  if (res.data.flag) {
                    this.form.finFundAccountDetailList = this.delListData(row.id, this.form.finFundAccountDetailList)
                    this.finSubjectManageCacheList = this.delListData(row.id, this.finSubjectManageCacheList)
                    this.msgSuccess(this.$t('删除成功'))
                  } else {
                    this.msgWarning(res.data.message)
                  }
                })
                return
              }).catch(() => {
                this.loading = false
              })
            },
            // 删除数据处理详情列表
            delListData(id, list) {
              var arr = []
              list.forEach(item => {
                if (item.id !== id) {
                  if (item.children.length > 0) {
                    item.children = this.delListData(id, item.children)
                    arr.push(item)
                  } else {
                    arr.push(item)
                  }
                }
              })
              return arr
            },
          // 删除按钮操作
          // deleteHandle(index, row) {
          //   // eslint-disable-next-line no-undef
          //   const id = row.id
          //   if (id !== undefined && id !== '' && id != null) {
          //     this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          //       confirmButtonText: this.$t('确定'),
          //       cancelButtonText: this.$t('取消'),
          //       type: 'warning'
          //     })
          //       .then(function() {
          //         return delRiskFamilyAccount(id)
          //       }).then(() => {
          //       this.form.riskFamilyAccountList.splice(index, 1)
          //       return this.msgSuccess(this.$t('删除成功'))
          //     })
          //       .catch(function() {})
          //   } else {
          //     this.form.riskFamilyAccountList.splice(index, 1)
          //   }
          // },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    accountCode: undefined,
                    accountName: undefined,
                    accountFullName: undefined,
                    startYearMonth: undefined,
                    fundId: undefined,
                    initialShare: undefined,
                    initialMoney: undefined,
                    accountingStandard: 'f12cb7c4772e44bf8582283382dacdcf',
                    remark: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined,
                    finFundAccountDetailList: []
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        this.form.finFundAccountDetailList = this.finSubjectManageCacheList
                        saveFinFundAccount(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                       this.locationError(document)
                    }
                }).catch(() => {
                    this.loading = false
                })
          },
          onChange(row) {
            this.setChildrenTreeData(row, this.finSubjectManageCacheList, 'edit')
            this.finSubjectManageCacheList = JSON.parse(JSON.stringify(this.finSubjectManageCacheList))
            this.$forceUpdate()
          },
          radioChange(e) {
            if (this.subjectType === e) {
              this.subjectType = ''
              this.form.finFundAccountDetailList = this.finSubjectManageCacheList
            } else {
              this.subjectType = e
              this.form.finFundAccountDetailList = this.filterTree(this.finSubjectManageCacheList, e, true)
            }
          },
          filterTree(arr, keyword, first = true) {
            if (first) {
              arr = JSON.parse(JSON.stringify(arr))
            }
            const emptyArr = []
            for (const item of arr) {
              if (item.subjectType.includes(keyword)) {
                if (item.children && Array.isArray(item.children) && item.children.length > 0) {
                  item.children = this.filterTree(item.children, keyword, false)
                }
                emptyArr.push(item)
              } else if (item.children && Array.isArray(item.children) && item.children.length > 0) {
                item.children = this.filterTree(item.children, keyword, false)
                if (item.children.length) {
                  emptyArr.push(item)
                }
              }
            }
            return emptyArr
          },
          isNoChildren(data) {
            if (!data.children) {
              return true
            } else if (data.children.length === 0) {
              return true
            }
            return false
          },
          countHj(data) {
            var nodes = data.children || []
            let total = 0
            for (let i = 0; i < nodes.length; i++) {
              total += nodes[i].openingAmount || 0
            }
            data.openingAmount = total
            return parseFloat(total.toFixed(2))
           }
        }
    }
</script>
<style lang="scss" scoped>
/deep/.subjectCode{
  .el-radio-button__inner{
    font-size: 12px!important;
    padding: 6px 20px !important;
    border-radius: 8px;
    background: #F4F4F4;
    border: 1px solid #F4F4F4;
    color: #898989;
    outline: none!important;
    outline-color: transparent!important;
    transition: unset!important;
    box-shadow: unset!important;
    border-left: 1px solid #F4F4F4;
  }
  .el-radio-button__orig-radio:checked+.el-radio-button__inner {
    font-size: 12px!important;
    background: rgba(24,144,255, 0.08);
    border: 1px solid #1890ff;
    color: #1890ff;
    position: relative;
    overflow: hidden;
    &::before{
      position: absolute;
      content: "";
      display: block;
      bottom: 2px;
      right: 2px;
      width: 4px;
      height: 7px;
      border-style: solid;
      border-color: #fff;
      border-width: 0 2px 2px 0;
      transform: rotate(45deg);
      z-index: 1;
    }
    &::after{
      position: absolute;
      content: "";
      display: block;
      bottom: -9px;
      right: -9px;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background: #1890ff;
      z-index: 0;
    }
  }
  .el-radio-button:focus:not(.is-focus):not(:active):not(.is-disabled) {
    box-shadow: unset!important;
  }
  .el-radio-button {
    margin-right: 10px;
    margin-bottom: 3px;
  }

}
</style>
